<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/2/11
 * Time: 0:03
 */

namespace app\api\logic;

use app\api\model\Company;
use think\Db;
use think\Validate;
use think\Hook;
class Order
{
    /**
     * 订单号生成
     * @return string
     */
    public function createSn(){
        $order_id_main = date('YmdHis') . rand(10000000,99999999);
        //订单号码主体长度
        $order_id_len  = strlen($order_id_main);
        $order_id_sum  = 0;
        for($i=0; $i<$order_id_len; $i++){
            $order_id_sum += (int)(substr($order_id_main,$i,1));
        }
        $order_sn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
        return $order_sn;
    }

    /**
     * 创建订单
     * @param array $data 订单数据
     * @param array $gpsData GPS数据
     * @param array $feeData 费用数据
     * @return array
     */
    public function createOrder($data,$gpsData,$feeData){
        $where['car_type_id'] = $data['car_type_id'];
        $where['state']       = 1;
        $data['order_no']     = $this->createSn();
        $data['order_time']   = date('Y-m-d H:i:s');
        $carTypeInfo          = Db::name('car_type')->where($where)->whereNull('delete_time')->find();
        if($data['special_type']==1){
            $data['order_state'] = 21;
        }
        // 下单类型为包车时目的地为包车名称
        if($data['booking_type']==2){
            $gpsData['to_addr'] = $carTypeInfo['car_type_name'];
        }
        list($code,$msg)     = $this->checkHasOrder($data['passenger_id'],$data['order_type'],$data['reorder']);
        if($code==0){
            return [0,$msg];
        }
        if($data['order_type']==1 && $data['pay_type'] == 3){//pay_type
            $quota       = (new Company())->getUseMoneyByPassenger($data['passenger_id']);
            $officeLeft  = $quota['quota'] - $quota['office_money'] - $feeData['pre_fee'] - $quota['office_lock_money'];
            // 非行政执法限制下单
            if($officeLeft<0 && $data['use_type']>1){
                return [0,132];
            }
        }
        if(empty($carTypeInfo)){
            return [0,131];
        }
        Db::startTrans();
        try {
            $order_id = Db::name('order')->insertGetId($data);
            $gpsData['order_id'] = $order_id;
            $feeData['order_id'] = $order_id;
            Db::name('order_gps')->insert($gpsData);
            Db::name('order_fee')->insert($feeData);
            Db::commit();
            $gpsData['order_no'] = $data['order_no'];
            if($data['order_type']==1){
                Hook::listen('use_car',$order_id);//公务订单绑定通知提醒审核
            }
            return [1,$gpsData];
        } catch (\Exception $e) {
            Db::rollback();
            return [0,$e->getMessage()];
        }
    }

    public function checkHasOrder($pid,$type,$re=0){
       return [1,'ok'];// if($re>0) 
//        $where['order_state'] = ['in','4,5,6,7,8,9'];
//        $where['order_type']  = $type;//根据订单类型
//        if($type<>3){
//            return [1,'ok'];
//        }
//        $order                = Db::name('order')->where('passenger_id',$pid)->where($where)->find();
//        if(!empty($order)){
//            return [0,130];
//        }else{
//            return [1,'ok'];
//        }
    }

    /**
     * 订单审核
     * @param $oid
     * @param $pid
     * @orderState
     * @note
     * @return array
     */
    public function approvalOrder($pid,$oid,$orderState=2,$note=''){
        $order    = Db::name('order')->where('order_id|order_no',$oid)->find();
        if(empty($oid)){
            return [0,404];
        }
        if($order['order_state']!=1){
            return [0,'订单状态异常'];
        }
        $oid      = $order['order_id'];
        if($pid != $order['approval_id']){
            return [0,'订单审核人员不符合'];
        }
        if($orderState==3 && empty($note)){
            return [0,'驳回必须填写原因'];
        }
        $data['approval_time'] = date('Y-m-d H:i:s', time());
        $data['order_state']   = $orderState;
        !empty($note) && $data['reject_note'] = $note;
        if($orderState==2){
            $payType     = $order['pay_type'];
            $fee         = Db::name('order_fee')->where('order_id',$oid)->value('pre_fee');
            $carUseMoney = (new Company())->getUseMoneyByPassenger($pid);
            if($payType==3 && $fee> ($carUseMoney['quota'] - $carUseMoney['office_money'] - $carUseMoney['office_lock_money']) && $order['use_type'] > 1){
                return [0,'公务额度不足'];
            }
            if($payType==2 && $fee> ($carUseMoney['unit_quota'] - $carUseMoney['company_money'] - $carUseMoney['company_lock_money'])){
                 return [0,'单位额度不足'];
            }
        }
        $ret  = Db::name('order')->where('order_id',$oid)->update($data);
        $code = $ret == 0 ? 0  : 1;
        $msg  = $ret == 0 ? '订单已经审核过' : 'ok';
        if($orderState==2 && $ret>0){
            Hook::listen('check_order',$oid);
        }
        if($orderState==3&& $ret>0){
            Hook::listen('reject_order',$oid);
        }
        return [$code,$msg];
    }

    public function addDispatchLog($oid,$did,$cid,$way=0){
        $data['add_time'] = date('Y-m-d H:i:s');
        $data['order_id'] = $oid;
        $data['driver_id'] = $did;
        $data['car_id'] = $cid;
        $data['dispatch_way'] = $way;
        Db::name('order_dispatch')->insert($data);
    }
}